/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pacoteconexao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
        

public class ConexaoMySQL {

    String url = "jdbc:mysql://localhost:3306/db_plastek";
    String usuario = "root";
    String senha = "123456";
    public Connection conexao = null;
    
    public void conectar(){
    try{
        //carregando o driver
        Class.forName("com.mysql.jdbc.Driver");
        //driver carregado
        try{
            conexao = DriverManager.getConnection(url,usuario,senha);
            //JOptionPane.showMessageDialog(null,"Sucesso na conexão");
        }catch(SQLException ex){
            JOptionPane.showMessageDialog(null,"Erro na conexão: "+ex);
        }
    }catch(ClassNotFoundException objErroDriver){
         JOptionPane.showMessageDialog(null,"Erro no Driver MySQL: "+objErroDriver);
        }
    
    }
    
    public void desconectar(){
        try{
            conexao.close();
            //JOptionPane.showMessageDialog(null,"Conexao encerrada");
        }catch(SQLException ex){
            Logger.getLogger(ConexaoMySQL.class.getName()).log(Level.SEVERE,null,ex);
            JOptionPane.showMessageDialog(null,"Erro na desconexão: "+ex);
        }
    }

   public ResultSet consultar(String sql) {
       PreparedStatement stmt = null;
       try{
           stmt = conexao.prepareStatement(sql);
           return stmt.executeQuery();
       } catch(SQLException ex){
           JOptionPane.showMessageDialog(null,"Erro na tentativa de consulta: "+ex);
           return null;
       }
    }
}
